

import 'package:erp/Entity/SupplierType.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/AccountStore.dart';
import 'package:erp/Store/SupplierStore.dart';
import 'package:erp/global.dart';

void registerSupplierTypeEvents(){
  globalBus.subscribe(Events.SUPPLIER_TYPE_SELECT_REQUEST, (bus, _) async {
    try {
      var supplierTypes = await externalInterface.getAllSupplierTypes(AccountStore.signInResult.token);
      SupplierStore.supplierTypes = supplierTypes;
      globalBus.publish(Events.SUPPLIER_TYPE_SELECT_SUCCESS, supplierTypes);
    }
    catch (exception){
      globalBus.publish(Events.SUPPLIER_TYPE_SELECT_ERROR, exception);
    }
  });

  globalBus.subscribe<SupplierType>(Events.SUPPLIER_TYPE_INSERT_REQUEST, (bus, data) async {
    try
    {
      var responseData = await externalInterface.addSupplierType(AccountStore.signInResult.token, data);
      SupplierStore.supplierTypes.add(responseData);
      globalBus.publish(Events.SUPPLIER_TYPE_INSERT_SUCCESS, responseData);
    }
    catch (exception){
      globalBus.publish(Events.SUPPLIER_TYPE_INSERT_ERROR, exception);
    }
  });

  globalBus.subscribe<SupplierType>(Events.SUPPLIER_TYPE_UPDATE_REQUEST, (bus, data) async {
    try{
      var responseData = await externalInterface.updateSupplierType(AccountStore.signInResult.token, data);
      var index = SupplierStore.supplierTypes.indexWhere((item) => item.id == data.id);
      SupplierStore.supplierTypes[index] = responseData;
      globalBus.publish(Events.SUPPLIER_TYPE_UPDATE_SUCCESS, responseData);
    }
    catch (exception){
      globalBus.publish(Events.SUPPLIER_TYPE_UPDATE_ERROR, Exception);
    }
  });

  globalBus.subscribe<SupplierType>(Events.SUPPLIER_TYPE_DELETE_REQUEST, (bus, data) async {
    try {
      var responseData = await externalInterface.deleteSupplierType(AccountStore.signInResult.token, data);
      SupplierStore.supplierTypes.removeWhere((item) => item.id == responseData.id);
      globalBus.publish(Events.SUPPLIER_TYPE_DELETE_SUCCESS, responseData);
    }
    catch (exception){
      globalBus.publish(Events.SUPPLIER_TYPE_DELETE_ERROR, exception);
    }
  });
}